package com.ruoyi.ffmpeg;

import org.apache.commons.lang3.ObjectUtils;
import org.bytedeco.ffmpeg.global.avcodec;
import org.bytedeco.ffmpeg.global.avutil;
import org.bytedeco.javacv.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ws.schild.jave.Encoder;
import ws.schild.jave.EncoderException;
import ws.schild.jave.MultimediaObject;
import ws.schild.jave.ScreenExtractor;
import ws.schild.jave.encode.AudioAttributes;
import ws.schild.jave.encode.EncodingAttributes;
import ws.schild.jave.encode.VideoAttributes;
import ws.schild.jave.info.AudioInfo;
import ws.schild.jave.info.MultimediaInfo;
import ws.schild.jave.info.VideoInfo;
import ws.schild.jave.info.VideoSize;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Paths;

public class FFmpegProcessor {

    private static final Logger logger = LoggerFactory.getLogger(FFmpegProcessor.class) ;

    /**
     * 这个方法的url地址都必须是一样的类型 同为post
     */
    public static void convertMediaToM3u8ByHttp(InputStream inputStream, String m3u8Url, String infoUrl) throws IOException {

        avutil.av_log_set_level(avutil.AV_LOG_INFO);
        FFmpegLogCallback.set();

        FFmpegFrameGrabber grabber = new FFmpegFrameGrabber(inputStream);
        grabber.start();

        FFmpegFrameRecorder recorder = new FFmpegFrameRecorder(m3u8Url, grabber.getImageWidth(), grabber.getImageHeight(), grabber.getAudioChannels());

        recorder.setFormat("hls");
        recorder.setOption("hls_time", "60");
        recorder.setOption("hls_list_size", "0");
        recorder.setOption("hls_flags", "delete_segments");
        recorder.setOption("hls_delete_threshold", "1");
        recorder.setOption("hls_segment_type", "mpegts");
        recorder.setOption("hls_segment_filename", "http://localhost:8080/oss/upload/test-%d.ts");
        //recorder.setOption("hls_key_info_file", infoUrl);

        // http属性
        recorder.setOption("method", "POST");

        //recorder.setFrameRate(25);
        //recorder.setGopSize(2 * 25);
        recorder.setVideoQuality(1.0);
        //recorder.setVideoBitrate(10 * 1024);
        //recorder.setVideoCodec(AV_CODEC_ID_H264);
        //recorder.setAudioCodec(avcodec.AV_CODEC_ID_AAC);
        //recorder.setVideoQuality(grabber.getVideoBitrate());
        recorder.setVideoBitrate(grabber.getVideoBitrate());
        recorder.setVideoCodec(grabber.getVideoCodec()) ;
        recorder.setAudioChannels(grabber.getAudioChannels());
        recorder.setFrameRate(grabber.getFrameRate());
        recorder.start();

        Frame frame;
        while ((frame = grabber.grabImage()) != null) {
            try {
                recorder.record(frame);
            } catch (FrameRecorder.Exception e) {
                e.printStackTrace();
            }
        }
        recorder.setTimestamp(grabber.getTimestamp());
        recorder.close();
        grabber.close();
    }

    /**
     * @param source  源文件
     * @param targetPath 转码后的路径
     */

    public static void convertVideoToMP4(File source, String targetPath) {
        MultimediaObject multimediaObject = new MultimediaObject(source);
        File target = new File(targetPath);

        try {
            MultimediaInfo info = multimediaObject.getInfo();
            VideoInfo videoInfo = info.getVideo();
            VideoSize size = videoInfo.getSize();

            //TODO 视频属性设置
            int maxBitRate = 128000;// 比特率
            int maxSamplingRate = 44100;// 音频采样频率
            int bitRate = 800000;// 比特率
            int maxFrameRate = 20;
            int maxWidth = 3280;

            VideoAttributes video = new VideoAttributes();
            //设置视频编码
            video.setCodec("h264");
            //设置音频比特率,单位:b (比特率越高，清晰度/音质越好，当然文件也就越大 800000 = 800kb)
            if(videoInfo.getBitRate() > bitRate){
                video.setBitRate(bitRate);
            }
            // 视频帧率：15 f / s  帧率越低，效果越差
            // 设置视频帧率（帧率越低，视频会出现断层，越高让人感觉越连续），视频帧率（Frame rate）是用于测量显示帧数的量度。所谓的测量单位为每秒显示帧数(Frames per Second，简：FPS）或“赫兹”（Hz）。
            if(videoInfo.getFrameRate() > maxFrameRate){
                video.setFrameRate(maxFrameRate);
            }
            // 限制视频宽高
            int width = videoInfo.getSize().getWidth();
            int height = videoInfo.getSize().getHeight();
            if(width > maxWidth){
                float rat = (float) width / maxWidth;
                video.setSize(new VideoSize(maxWidth,(int)(height/rat)));
            }

            AudioAttributes audio = new AudioAttributes();
            AudioInfo audioInfo = multimediaObject.getInfo().getAudio();
            //设置编码器名称
            audio.setCodec("aac");
            // 设置通用编码格式10                   audio.setCodec("aac");
            // 设置最大值：比特率越高，清晰度/音质越好
            // 设置音频比特率,单位:b (比特率越高，清晰度/音质越好，当然文件也就越大 128000 = 182kb)
            if(audioInfo.getBitRate() > maxBitRate){
                audio.setBitRate(new Integer(maxBitRate));
            }
            // 设置重新编码的音频流中使用的声道数（1 =单声道，2 = 双声道（立体声））。如果未设置任何声道值，则编码器将选择默认值 0。
            audio.setChannels(audioInfo.getChannels());
            // 采样率越高声音的还原度越好，文件越大
            // 设置音频采样率，单位：赫兹 hz
            // 设置编码时候的音量值，未设置为0,如果256，则音量值不会改变
            // audio.setVolume(256);
            if(audioInfo.getSamplingRate() > maxSamplingRate){
                audio.setSamplingRate(maxSamplingRate);
            }
            EncodingAttributes attrs = new EncodingAttributes();
            //设置转换后的格式
            //attrs.setFormat("mp4");
            attrs.setOutputFormat("mp4") ;
            attrs.setAudioAttributes(audio);
            attrs.setVideoAttributes(video);
            attrs.setDecodingThreads(Runtime.getRuntime().availableProcessors()/2);
            attrs.setEncodingThreads(Runtime.getRuntime().availableProcessors()/2);
            Encoder encoder = new Encoder();
            encoder.encode(multimediaObject, target, attrs);
            //花费毫秒数

            MultimediaObject multimediaObjectOfter = new MultimediaObject(Paths.get(targetPath).toFile());
            MultimediaInfo info1 = multimediaObjectOfter.getInfo();
            VideoInfo video1 = info1.getVideo();
            VideoSize size1 = video1.getSize();
        } catch (EncoderException e) {
            e.printStackTrace();
        }
    }

    /**
     * @param url  源文件
     * @param targetPath 转码后的路径
     */

    public static void convertVideoToMP4(URL url, String targetPath) {
        MultimediaObject multimediaObject = new MultimediaObject(url);
        File target = new File(targetPath);
        try {
            MultimediaInfo info = multimediaObject.getInfo();
            VideoInfo videoInfo = info.getVideo();
            VideoSize size = videoInfo.getSize();

            //TODO 视频属性设置
            int maxBitRate = 128000;// 比特率
            int maxSamplingRate = 44100;// 音频采样频率
            int bitRate = 800000;// 比特率
            int maxFrameRate = 20;
            int maxWidth = 3280;

            VideoAttributes video = new VideoAttributes();
            //设置视频编码
            video.setCodec("h264");
            //设置音频比特率,单位:b (比特率越高，清晰度/音质越好，当然文件也就越大 800000 = 800kb)
            if(videoInfo.getBitRate() > bitRate){
                video.setBitRate(bitRate);
            }
            // 视频帧率：15 f / s  帧率越低，效果越差
            // 设置视频帧率（帧率越低，视频会出现断层，越高让人感觉越连续），视频帧率（Frame rate）是用于测量显示帧数的量度。所谓的测量单位为每秒显示帧数(Frames per Second，简：FPS）或“赫兹”（Hz）。
            if(videoInfo.getFrameRate() > maxFrameRate){
                video.setFrameRate(maxFrameRate);
            }
            // 限制视频宽高
            int width = videoInfo.getSize().getWidth();
            int height = videoInfo.getSize().getHeight();
            if(width > maxWidth){
                float rat = (float) width / maxWidth;
                video.setSize(new VideoSize(maxWidth,(int)(height/rat)));
            }

            AudioAttributes audio = new AudioAttributes();
            AudioInfo audioInfo = multimediaObject.getInfo().getAudio();
            //设置编码器名称
            audio.setCodec("aac");
            // 设置通用编码格式10                   audio.setCodec("aac");
            // 设置最大值：比特率越高，清晰度/音质越好
            // 设置音频比特率,单位:b (比特率越高，清晰度/音质越好，当然文件也就越大 128000 = 182kb)
            if(audioInfo.getBitRate() > maxBitRate){
                audio.setBitRate(new Integer(maxBitRate));
            }
            // 设置重新编码的音频流中使用的声道数（1 =单声道，2 = 双声道（立体声））。如果未设置任何声道值，则编码器将选择默认值 0。
            audio.setChannels(audioInfo.getChannels());
            // 采样率越高声音的还原度越好，文件越大
            // 设置音频采样率，单位：赫兹 hz
            // 设置编码时候的音量值，未设置为0,如果256，则音量值不会改变
            // audio.setVolume(256);
            if(audioInfo.getSamplingRate() > maxSamplingRate){
                audio.setSamplingRate(maxSamplingRate);
            }
            EncodingAttributes attrs = new EncodingAttributes();
            //设置转换后的格式
            //attrs.setFormat("mp4");
            attrs.setOutputFormat("mp4") ;
            attrs.setAudioAttributes(audio);
            attrs.setVideoAttributes(video);
            attrs.setDecodingThreads(Runtime.getRuntime().availableProcessors()/2);
            attrs.setEncodingThreads(Runtime.getRuntime().availableProcessors()/2);
            Encoder encoder = new Encoder();
            encoder.encode(multimediaObject, target, attrs, new EncoderProgressListenerImpl());
            //花费毫秒数
            MultimediaObject multimediaObjectOfter = new MultimediaObject(Paths.get(targetPath).toFile());
            MultimediaInfo info1 = multimediaObjectOfter.getInfo();
            VideoInfo video1 = info1.getVideo();
            VideoSize size1 = video1.getSize();
        } catch (EncoderException e) {
            e.printStackTrace();
        }
    }

    /**
     * 截取视频的一针作为封面图
     *
     * @param file   视频文件
     * @param thumbnailPath 截取图片保存路径
     * @return
     */

    public void getVideoInfoAndGenerateThumbnail(File file, String thumbnailPath, long location) {
        MultimediaObject multimediaObject = new MultimediaObject(file);
        try {
            MultimediaInfo info = multimediaObject.getInfo();
            VideoInfo videoInfo = info.getVideo();
            logger.info("获取视频时长：{}", info.getDuration() / 1000);
            if (ObjectUtils.isNotEmpty(videoInfo)) {
                VideoSize size = videoInfo.getSize();
                int width = size.getWidth();
                int height = size.getHeight();
                logger.info("视频宽：{} 视频高{}", width, height);
                logger.info("比特率：{}", videoInfo.getBitRate() / 1000);
                ScreenExtractor screenExtractor = new ScreenExtractor();
                File target = new File(thumbnailPath);
                //截取视频作为图片保存
                /**
                 *第一个参数 视频源文件信息类
                 * 第二个参数 截取的宽度
                 * 第三个参数 截取的高度
                 * 第四个参数 截取的是那一帧
                 * 第五个参数是 截取的图片质量 1-31 数字越小质量越高
                 *
                 **/
                double v = 0.9;
                location = new Double(multimediaObject.getInfo().getDuration() * v).longValue();
                screenExtractor.renderOneImage(multimediaObject, size.getWidth(), size.getHeight(), location, target, 31);
            }
        } catch (EncoderException e) {
            e.printStackTrace();
        }

    }

}
